from django.contrib.auth import login, logout, authenticate
from django import http
from aijiazufang.utils.qiniuyun.qiniu_storage import img_url
from aijiazufang.utils.qiniuyun.qiniu_storage import storage
from aijiazufang.utils.view import LoginRequiredMixin
from django.views import View
import json, re, logging
from django.http import JsonResponse
from django_redis import get_redis_connection
from users.models import User

# 日志输出器
logger = logging.getLogger('django')


class UserDataView(View):
    # 用户中心
    def get(self, request):
        # 提供个人信息界面
        # 获取界面需要的数据，进行拼接

        user = request.user
        # 判断是否登录
        if user.is_authenticated:

            data = {

                "avatar_url": request.user.avatar.name,
                # "create_time": user.create_time,
                "mobile": user.mobile,
                "name": user.username,
                "user_id": user.id_card
            }
            return JsonResponse({
                "data": data,
                "errmsg": "OK",
                "errno": 0
            })
        else:
            return JsonResponse({"errmsg": "用户未登录",
                                 "errno": 4101})


class AvatarView(LoginRequiredMixin, View):
    """
    上传头像
    请求方法: POST
    请求参数: avatar [头像文件]
    """

    def post(self, request):
        """
        上传头像接口
        :param request: 请求对象
        :return: 响应对象
        """
        img = request.FILES.get('avatar')
        img_data = img.read()
        img_url = 'http://qcz5dw5aq.bkt.clouddn.com/'
        # 校验参数:
        if not img_data:
            return http.JsonResponse({"errno": "4002", "errmsg": "无数据"})
        # 上传图片:
        file_index = storage(img_data)
        # 报存数据:
        try:
            request.user.avatar = img_url + file_index
            request.user.save()
        except BaseException as error:
            logger.error(error)

        return http.JsonResponse({"data": {"avatar_url": request.user.avatar.name},
                                  "errno": "0",
                                  "errmsg": "头像上传成功"})


class ModifyUsernameView(LoginRequiredMixin, View):  # 这里需要导入mixin类
    """
        修改用户名
        请求方法: PUT
        请求参数: name
    """

    def put(self, request):
        """
            修改用户名接口
            :param request: 请求对象
            :return: 响应对象
        """
        # 接收参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('name')

        # 校验参数
        if not username:
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        # 参数格式匹配
        if not re.match(r'^[A-Za-z0-9_\u4e00-\u9fa5]{2,16}$', username):
            return JsonResponse({'errno': 4103, 'errmsg': '用户名格式错误'})

        # 查找是否有重复用户名
        count = User.objects.filter(username=username).count()
        if count:
            return JsonResponse({'errno': 4003, 'errmsg': '用户名已存在'})

        user = request.user
        try:

            # 数据库操作,修改用户名并保存
            user.username = username
            user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4302, 'errmsg': '写入数据库失败,修改用户名失败'})

        # 响应对象
        return JsonResponse({'errno': 0, 'errmsg': '用户名修改成功'})


class LoginView(View):

    # 用户登录
    def post(self, request):
        '''实现接口登录'''
        # 接收参数
        dict = json.loads(request.body.decode())
        password = dict.get('password')
        username = dict.get('mobile')

        if not all([username, password]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        # 单个校验
        if not re.match(r'^[A-Za-z0-9_\u4e00-\u9fa5]{4,16}$', username):
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'mobile格式有误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'password格式有误'})

        # 验证是否能够登录
        user = authenticate(username=username,
                            password=password)
        if not user:
            return JsonResponse({'errno': 4105, 'errmsg': '用户名或密码错'})

        #  状态保持
        login(request, user)
        # 返回json
        response = JsonResponse({'errno': 0,
                                 'errmsg': '登录成功'})
        return response

    def get(self, request):
        '''判断用户是否登录'''

        user = request.user
        # 判断是否登录
        if user.is_authenticated:
            return JsonResponse({
                'errno': 0,
                'errmsg': '已登录',
                'data': {
                    'name': request.user.username,
                    'user_id': request.user.id
                }
            })

        else:
            return JsonResponse({
                'errno': '4101',
                'errmsg': '未登录'
            })

    # 用户退出登录
    def delete(self, request):
        # 实现退出登录逻辑
        # 判断用户是否登录：
        if request.user.is_authenticated:
            # 　清除session里的信息
            logout(request)
            # 创建response对象
            response = JsonResponse({'errno': 0,
                                     'errmsg': '退出登录成功'})
            # 调用对象的delete_cookie　方法，　清除cookie
            response.delete_cookie('username')

            # 返回响应
            return response
        else:
            return JsonResponse({'errno': 4101,
                                 'errmsg': '用户未登录，请先登录'})


class AuthView(LoginRequiredMixin, View):

    def post(self, request):
        '''用户实名认证'''
        # 接收参数
        dict_json = json.loads(request.body.decode())
        real_name = dict_json.get('real_name')
        id_card = dict_json.get('id_card')

        # 校验参数
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})

        if not re.match(r'^([\u4E00-\u9FA5]+|[a-zA-Z]+)$', real_name):
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'real_name格式有误'})

        if not re.match(
                r'^[1-9]\d{5}(18|19|20|(3\d))\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$', id_card):
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'id_card格式有误'})
        # 保存数据
        try:
            request.user.real_name = real_name
            request.user.id_card = id_card
            request.user.save()

        except Exception as e:

            return JsonResponse({'errno': 4001, 'errmsg': '保存数据失败'})

        data = {'real_name': real_name, 'id_card': id_card}

        # 返回数据
        return JsonResponse({
            "errno": 0,
            "errmsg": "认证信息保存成功",
            'data': data,
        })

    def get(self, request):

        # 提取对象
        user = request.user

        data = {'real_name': user.real_name, 'id_card': user.id_card}

        # 返回数据
        return JsonResponse({
            "errno": 0,
            "errmsg": "查询成功",
            'data': data,
        })


class RegistView(View):

    def post(self, request):
        # 接收参数

        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        phonecode = dict.get('phonecode')
        password = dict.get('password')

        # 判断是否缺少必传参数
        if not all([mobile, phonecode, password]):
            return JsonResponse({
                'errno': 4103,
                'errmsg': '缺少必传参数'
            })

        # 检查手机号码格式是否正确
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({
                'errno': 4103,
                'errmsg': '手机号格式错误'
            })
        # 判断密码格式
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({
                'errno': 4106,
                'errmsg': '密码错误'
            })

        # 创建redis对象
        redis_conn = get_redis_connection('verify_code')
        # 从redis中获取保存的短信验证码
        sms_code_server = redis_conn.get(f'sms_{mobile}')

        # 判断验证码是否存在
        if not sms_code_server:
            return JsonResponse({
                'errno': 4002,
                'errmsg': '无数据'
            })

        # 把redis中存储的数据取出来与前端发送的比较
        if sms_code_server.decode() != phonecode:
            return JsonResponse({
                'errno': 400,
                'errmsg': '数据错误'
            })

        # 保存到数据库
        try:

            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )

        except Exception as e:
            logger.error(e)
            return JsonResponse({'errno': 4004,
                                 'errmsg': '保存数据库失败'})
        login(request, user)
        return JsonResponse({
            "errno": "0",
            "errmsg": "注册成功"
        })
